class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

// 递归
function maxDepth(root: TreeNode | null): number {
    if (root === null) return 0;

    const left = maxDepth(root.left);
    const right = maxDepth(root.right);

    return Math.max(left, right) + 1;// 每次递归返回左右子树的最大深度+1
};
// 迭代 队列
function maxDepth1(root: TreeNode | null): number {
    if (root === null) return 0;

    const queue = [root];
    let depth = 0;

    while (queue.length) {
        const size = queue.length;
        for (let i = 0; i < size; i++) {
            const node = queue.shift();// 出队
            if (node!.left) queue.push(node!.left);
            if (node!.right) queue.push(node!.right);
        }
        depth++;
    }

    return depth;
}

// 迭代 栈
function maxDepthDFS(root: TreeNode | null): number {
    if (root === null) return 0;

    const stack: [TreeNode, number][] = [[root, 1]];
    let maxDepth = 0;

    while (stack.length) {
        const [node, currentDepth] = stack.pop()!;

        // 更新最大深度
        maxDepth = Math.max(maxDepth, currentDepth);

        // 将子节点入栈
        if (node.right) {
            stack.push([node.right, currentDepth + 1]);
        }
        if (node.left) {
            stack.push([node.left, currentDepth + 1]);
        }
    }

    return maxDepth;
}
